package shiyan5;

import Calculate.SuffixExpression;

import javax.crypto.Cipher;
import java.io.*;
import java.net.Socket;
import java.security.Key;
import java.util.Scanner;

public class SocketClient3 {
    public static void main(String[] args) throws Exception {
        //1.建立客户端Socket连接，指定服务器位置和端口
        // Socket socket = new Socket("localhost",8080);
        Socket socket = new Socket("192.168.43.40",8800);
        Scanner scan = new Scanner(System.in);
        //2.得到socket读写流
        OutputStream outputStream = socket.getOutputStream();
        //  PrintWriter printWriter = new PrintWriter(outputStream);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
        //输入流
        InputStream inputStream = socket.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
        //3.利用流按照一定的操作，对socket进行读写操作

        System.out.print("请输入您的中缀表达式：");
        String nifixexpression = scan.nextLine();
        SuffixExpression suffixexpression = new SuffixExpression();
        String houzhui = suffixexpression.SuffixExpression(nifixexpression);

        FileInputStream f=new FileInputStream("key1.dat");
        ObjectInputStream b=new ObjectInputStream(f);
        Key k=(Key)b.readObject( );
        Cipher cp=Cipher.getInstance("shiyan5.AES");
        cp.init(Cipher.ENCRYPT_MODE, k);
        byte ptext[]=houzhui.getBytes("UTF8");
        System.out.print("字节数组编码方式:" + "\t");
        for(int i=0;i<ptext.length;i++){
            System.out.print(ptext[i]+" ");
        }
        System.out.print("\n" + "加密内容：" + "\t");
        byte ctext[]=cp.doFinal(ptext);
        for(int i=0;i<ctext.length;i++){
            System.out.print(ctext[i] +" ");
        }

        outputStream.write(ctext);
        outputStream.flush();
        socket.shutdownOutput();
        //接收服务器的响应
        String reply = null;
        while (!((reply = bufferedReader.readLine()) ==null)){
            System.out.println("\n接收来自虚拟机服务器的信息为：" + reply);
        }

        //4.关闭资源
        bufferedReader.close();
        inputStream.close();
        outputStreamWriter.close();
        //printWriter.close();
        outputStream.close();
        socket.close();
    }
}
